/**
 * create by young (young2f@outlook.com) on 2024/4/21
 */
'use strict';
const base = require('../base/controllerBase');
const _stringUtils = require('../utils/stringUtils');

class DictController extends base {
  async createDict() {
    const { ctx, service } = this;
    try {
      const { body } = ctx.request;
      const model = {
        tenantCode: { type: 'string' },
        type: { type: 'string' },
      };

      ctx.validate(model, body);
      body.code = _stringUtils.getCode('DIC');
      const { table } = body;
      const result = await ctx.app.dbs.insert('Dict', body);
      ctx.body = { status: 'ok', result };
      ctx.status = 200;
    } catch (e) {
      console.error(e);
      const _message = e && e.message ? e.message : this.ERROR_MSG;
      ctx.body = { status: 'error', message: _message, result: e };
      ctx.status = 200;
    }
  }

  async deleteDict() {
    const { ctx, service } = this;
    try {
      const { body } = ctx.request;
      const model = {
        tenantCode: { type: 'string' },
        code: { type: 'string' },
      };

      ctx.validate(model, body);
      const { table, code, tenantCode } = body;
      const result = await ctx.app.dbs.deleteOne('Dict', { code, tenantCode });
      ctx.body = { status: 'ok', result };
      ctx.status = 200;
    } catch (e) {
      console.error(e);
      const _message = e && e.message ? e.message : this.ERROR_MSG;
      ctx.body = { status: 'error', message: _message, result: e };
      ctx.status = 200;
    }
  }

  async updateDict() {
    const { ctx, service } = this;
    try {
      const { body } = ctx.request;
      const model = {
        tenantCode: { type: 'string' },
        code: { type: 'string' },

      };

      ctx.validate(model, body);
      const { code, tenantCode } = body;
      const result = await ctx.app.dbs.updateOne('Dict', { code, tenantCode }, body);
      ctx.body = { status: 'ok', result };
      ctx.status = 200;
    } catch (e) {
      console.error(e);
      const _message = e && e.message ? e.message : this.ERROR_MSG;
      ctx.body = { status: 'error', message: _message, result: e };
      ctx.status = 200;
    }
  }

  async findDicts() {
    const { ctx, service } = this;
    try {
      const { body } = ctx.request;
      const model = {
        tenantCode: { type: 'string' },
        type: { type: 'string' },
      };
      console.log('find dicts', body);
      ctx.validate(model, body);
      const { tenantCode, type } = body;
      const result = await ctx.app.dbs.find('Dict', { type, tenantCode });

      ctx.body = { status: 'ok', result };
      ctx.status = 200;
    } catch (e) {
      console.error(e);
      const _message = e && e.message ? e.message : this.ERROR_MSG;
      ctx.body = { status: 'error', message: _message, result: e };
      ctx.status = 200;
    }
  }
}

module.exports = DictController;
